﻿using log4net.Config;
using Microsoft.Win32;
using MonitorEquipmentFrm.View;
using RFIDReaderDll; 
using smforj.common.model;
using smforj.common.service;
using smforj.common.util; 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace MonitorEquipmentFrm
{
    public partial class MainForm : Telerik.WinControls.UI.ShapedForm, IMonitorClient
    {

        private log4net.ILog log = log4net.LogManager.GetLogger("MainForm");
        /// <summary>
        /// 数据列表
        /// </summary>
        private List<DataTable> dtList = new List<DataTable>();
        private List<IMonitor> monitorList = new List<IMonitor>();

        private const int OK = 0; 

        /// <summary>
        /// 设备
        /// </summary>
        private IEquipment equiment;


        private Thread uploadData = null; 

        public MainForm()
        {
            InitializeComponent();
            init();
        }

        /// <summary>
        /// 初始化相关控件信息
        /// </summary>
        private void init()
        {
            try
            {
              
                String configFile = AppDomain.CurrentDomain.BaseDirectory + @"Log.config";
                XmlConfigurator.Configure(new System.IO.FileInfo(configFile)); 
                //设备接口
                equiment = new CEquipment();  
               
                this.SizeChanged += MainFrm_SizeChanged;
                this.FormClosing += MainFrm_FormClosing;
                //更新Form Title
                UpdateTitle();
                this.Load += MainForm_Load;  
                LoadEquipment(); 

                ThemeResolutionService.ApplyThemeToControlTree(this, this.highContrastBlackTheme1.ThemeName);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message);
                ShowError("启动界面异常："+ex.Message, "启动界面异常"); 
            }
        }

        private void ShowError(String Error,String showInfo)
        {    
            lerror.Text = showInfo;
            lerror.ToolTipText = Error;
        }


        public void UpdateTitle()
        {
            this.Text = String.Format("盛世龙图{0}监控系统", getType(GlobalCache.TType).ToString()); 
            this.radTitleBar1.Text = this.Text;
        } 
        /// <summary>
        /// 加载设备
        /// </summary>
        private void LoadEquipment()
        {
            List<ConnConfig> list = equiment.GetEquipList();
             
            int index = 0; 
            this.pgData.Pages.Clear();
            foreach (ConnConfig cc in list)
            {
                if (cc.Type == GlobalCache.TType)
                    addPage(cc, index++);
            }
        }
               
        /// <summary>
        /// 添加Page文档
        /// </summary>
        /// <param name="cc">设备配置信息</param>
        private void addPage(ConnConfig cc,int index)
        { 
            RadPageViewPage pvg = new RadPageViewPage(); 
            RadGridView rgv = new Telerik.WinControls.UI.RadGridView();
            rgv.SuspendLayout(); 
            pvg.Controls.Add(rgv); 
            pvg.SuspendLayout();
            this.pgData.Controls.Add(pvg);
            this.pgData.SelectedPage = pvg;  

            pvg.Location = new System.Drawing.Point(10, 37); 
            pvg.Name = cc.Ip;
            pvg.Size = new System.Drawing.Size(783, 422);
            pvg.Text = String.Format("{0} {1}-{2}", cc.Ip, cc.Location, getType(GlobalCache.TType).ToString());
            pvg.TabIndex = index;
            pvg.Dock = DockStyle.Fill;
            // 
            // rgc
            // 
            rgv.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(219)))), ((int)(((byte)(254)))));
            rgv.Cursor = System.Windows.Forms.Cursors.Default;
            rgv.Dock = System.Windows.Forms.DockStyle.Fill;
            rgv.Font = new System.Drawing.Font("Segoe UI", 8.25F);
            rgv.ForeColor = System.Drawing.Color.Black;
            rgv.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            rgv.Location = new System.Drawing.Point(0, 0);
            rgv.Margin = new System.Windows.Forms.Padding(4); 
            // 
            // rgc
            // 
            rgv.MasterTemplate.AllowAddNewRow = false;
            rgv.MasterTemplate.AllowColumnReorder = false;
            rgv.MasterTemplate.AllowColumnResize = false;
            rgv.MasterTemplate.AllowDragToGroup = false;
            rgv.MasterTemplate.AllowRowResize = false;
            rgv.MasterTemplate.EnableGrouping = false;
            rgv.MasterTemplate.EnableSorting = false;
            rgv.MasterTemplate.ShowRowHeaderColumn = false;
            rgv.Name = "rgvinfo" + index;
            rgv.ReadOnly = true;
            rgv.RightToLeft = System.Windows.Forms.RightToLeft.No;
            rgv.ShowGroupPanel = false;
            rgv.Size = new System.Drawing.Size(787, 442);
            rgv.TabIndex = index;
            rgv.Text = "radGridView1"; 
            DataTable dt = BindGrid(rgv); 

            //添加对象信息
            dtList.Add(dt);

            IMonitor monitor = MonitorFactory.CreateMonitor(getType(GlobalCache.TType), this);
            monitor.SetEquementInfo(new EquementInfo() { IConnConfig = cc, Index = index - 1, IDateTable = dt, 
                Ant1 = 10, Ant2 = 10, Ant3 = 10, Ant4 = 10 , AntnnaNumber = GlobalCache.AntnnaNumber});

            monitorList.Add(monitor);

        } 

        /// <summary>
        /// 获取监控类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public MonitorType getType(String type)
        {
            return (MonitorType)Enum.Parse(typeof(MonitorType), type, true);
        }

        void MainForm_Load(object sender, EventArgs e)
        { 
            //设置开机启动
            //ThreadPool.QueueUserWorkItem(new WaitCallback(AutoRun), true);  

            //上传数据
            //uploadData = new Thread(new ThreadStart(UploadData));
            //uploadData.Start();  

            //更新checked
            if (GlobalCache.TType == "2")
            {
                this.rmistation.Visibility = ElementVisibility.Visible;
                this.rmistation.IsChecked = true; 

                this.rmiFitting.Visibility = this.rmiWardrobe.Visibility = ElementVisibility.Hidden;
                this.rmiFitting.IsChecked = this.rmiWardrobe.IsChecked = false;

                this.rpvpinfo.Enabled = false;
                this.rpvpinfo.Hide();
            }
            else 
                if (GlobalCache.TType == "0")
            {
                this.rmiWardrobe.Visibility = ElementVisibility.Visible; 
                this.rmiWardrobe.IsChecked = true;

                this.rmistation.Visibility = this.rmiFitting.Visibility = ElementVisibility.Hidden;
                this.rmistation.IsChecked = this.rmiFitting.IsChecked = false;

                //this.rpvpinfo.Enabled = false;
                //this.rpvpinfo.Hide(); 
                this.rpvgstation.Enabled = false;
                this.rpvgstation.Hide();
            }else
            {
                this.rmiFitting.Visibility = ElementVisibility.Visible;
                this.rmiFitting.IsChecked = true;

                this.rmistation.Visibility = this.rmiWardrobe.Visibility = ElementVisibility.Hidden;
                this.rmistation.IsChecked = this.rmiWardrobe.IsChecked = false;

                this.rmiFitting.IsChecked = true;
                this.btnFitting.Enabled = true;

                this.rpvgstation.Enabled = false;
                this.rpvgstation.Hide();
            }

            this.WindowState = FormWindowState.Normal;

            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private IUpload GetService()
        {
            IUpload service = null;
            if (GlobalCache.TType == "0") 
                service = new WardRobeServiceImpl(); 
            else 
                service = new FittingServiceImpl(); 

            return service;
        }

        /// <summary>
        /// 服务
        /// </summary>
        private static IUpload service = null; 
        private static object lockObj = new object();
        private void UploadData()
        {
            Thread.Sleep(1000);

            service = GetService();
            while (true)
            {
                lock (lockObj)
                { 
                    try
                    {
                        service.UploadData();
                    }
                    catch (Exception ex)
                    {
                        log.Error("上传数据异常：" + ex.Message);
                        UpdateMessage("上传数据异常：" + ex.Message);
                    } 
                } 
                //10秒同步一次
                Thread.Sleep(1000*10);
            }
        }


        #region 显示信息 

        private DataTable BindGrid(RadGridView rgv) 
        {
            DataTable dtt = CreateDataTable(); 

            GridViewImageColumn imageColumn = new GridViewImageColumn("cimage"); 
            imageColumn.ImageLayout = ImageLayout.Zoom; 
            imageColumn.MaxWidth = 24; 
            imageColumn.MinWidth = 24;
            imageColumn.Width = 24; 
            imageColumn.HeaderTextAlignment = ContentAlignment.MiddleCenter; 
            imageColumn.HeaderText = "";
            imageColumn.HeaderImage = Properties.Resources.cnn_sccnn_03__6_;
            GridViewTextBoxColumn cinfo = new GridViewTextBoxColumn("cinfo");
            cinfo.Width = 745;
            cinfo.HeaderText = "信息"; 
            cinfo.HeaderTextAlignment = ContentAlignment.MiddleLeft;

            rgv.Columns.Add(imageColumn);
            rgv.Columns.Add(cinfo); 
            //radGridView1.MasterTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill; 
            rgv.DataSource = dtt; 

            rgv.Refresh();
            return dtt;
        }

        private delegate void myDelegate(InfoType it, String msg, DataTable dt);//定义委托
         
        /// <summary>
        /// 显示信息到界面 当界面信息数量达到1000条时自动清空
        /// </summary>
        /// <param name="it">类型</param>
        /// <param name="msg">显示的信息</param>
        private void showInfo(InfoType it, String msg,DataTable dt)
        {
            if (this.InvokeRequired && this.IsHandleCreated)
            {
                this.Invoke(new myDelegate(showInfo), new object[] { it, msg , dt});
            }
            else
            {
                lock (dt)
                {
                    //大于1000 清空
                    if (dt.Rows.Count > 1000)
                        dt.Rows.Clear();
                    DataRow row = dt.NewRow();
                    switch (it)
                    {
                        case InfoType.Info:
                            row["cimage"] = Properties.Resources.info_blue_32;
                            break;
                        case InfoType.Error:
                            row["cimage"] = Properties.Resources.error_red_32;
                            break;
                        case InfoType.Warning:
                            row["cimage"] = Properties.Resources.problem_yellow_32;
                            break;
                    }
                    row[1] = string.Format("   [{0}] {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg);
                    dt.Rows.InsertAt(row, 0);
                    dt.AcceptChanges();
                }
            }
        }

        private DataTable CreateDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("cimage", typeof(Image));
            table.Columns.Add("cinfo", typeof(string));
            return table;
        } 
        #endregion


        #region 关闭窗口相关

        //初始化退出标识
        private DialogResult result = DialogResult.No;
        //Yes关闭窗口，No最小化窗口
        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            if (result == DialogResult.Yes)
            { 
                e.Cancel = false; 
                //Application.Exit();
                System.Environment.Exit(0); 
            }
            else
            {
                e.Cancel = true; 
            }
        } 

        private void MainFrm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                mHide(); 
            }
        }

        /// <summary>
        /// 最小化程序
        /// </summary>
        private void mHide()
        {
            this.Hide();
            this.notifyIcon1.Visible = true;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = false;
        }

        private void radTitleBar1_Close(object sender, EventArgs args)
        {
            mHide();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            result = MessageBox.Show("确认退出窗口吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (result == System.Windows.Forms.DialogResult.Yes)
                this.Close();
        } 

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                result = System.Windows.Forms.DialogResult.Yes;
                this.mClose();
            }
        }
        #endregion 

        #region 开机自启动

        private Boolean isAutoFlag = false;
        private String appName = "MonitorEquipment";

        /// <summary>
        /// 开机自己启动
        /// </summary>
        private void AutoRun(Object isAutoRun)
        {
            Thread.Sleep(1000);
            if (isAutoFlag)
                return;
            isAutoFlag = true;
            string path = Application.ExecutablePath;
            try
            { 
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = Registry.LocalMachine.OpenSubKey(@"\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (rk2 == null)
                    rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                object obj = rk2.GetValue(appName);
                if ((Boolean)isAutoRun && obj == null) 
                    rk2.SetValue(appName, path); 
                else
                    rk2.DeleteValue(appName, false);
                rk2.Close();
                rk.Close();
            }
            catch (Exception ex)
            {
                //this.radLabelError.Text = "设置开机启动异常：" + ex.Message;
                log.Error("设置开机启动异常：" + ex.Message);
            }
            isAutoFlag = false;
        }
        #endregion 
        
        private void cbbstart_Click(object sender, EventArgs e)
        {
            CommandBarButton cbb = (CommandBarButton)sender;
            if (cbb.Text == "开始服务")
            {
                int iRes = 0;
                //只要有启动成功的则进行
                Boolean isStarted = false;
                foreach (IMonitor monitor in monitorList)
                {
                    iRes = monitor.StartServer();
                    if (iRes != OK)
                    {
                        UpdateMessage("开启失败:" + monitor.GetEquementInfo().IConnConfig.Ip);
                    }
                    else
                    {
                        isStarted = true;
                    }
                }
                if (isStarted)
                {
                    cbb.Text = "停止服务";
                    cbb.Image = Properties.Resources.Stop_16;
                }
            }
            else
            {
                int iRes = 0;
                Boolean isEnded = false;
                foreach (IMonitor monitor in monitorList)
                {
                    iRes = monitor.StopServer();
                    if (iRes != OK)
                    {
                        UpdateMessage("关闭失败:" + monitor.GetEquementInfo().IConnConfig.Ip);
                    }
                    else
                    {
                        isEnded = true;
                    }
                }
                if (isEnded)
                {
                    cbb.Text = "开始服务";
                    cbb.Image = Properties.Resources.Start_16;
                }
            }
        }  
         

        private void cbbexit_Click(object sender, EventArgs e)
        {
            result = System.Windows.Forms.DialogResult.Yes;
            this.mClose();
        }

        private void mClose()
        {
            foreach (IMonitor monitor in monitorList)
                if (monitor.GetStatus() == OK)
                {
                    int iRes = monitor.StopServer();
                    if (iRes != OK)
                    {
                        UpdateMessage("关闭失败:"+monitor.GetEquementInfo().IConnConfig.Ip);
                    }
                }

            //try
            //{
            //    LoginResponse lr = Program.loginService.logout(GlobalCache.loginUser.access_token);
            //    if (!lr.isSuccess)
            //        MessageBox.Show(lr.message);

            //    uploadData.Abort();
            //}
            //catch
            //{

            //}
            this.Close(); 
        }

        public void UpdateMessage(Info info, IMonitor monitor)
        {
            if (info != null && monitor != null) 
                this.showInfo(info.type,info.message,monitor.GetEquementInfo().IDateTable); 
        }
        
        public void UpdateMessage(String message)
        {
            this.lerror.Text = message;
        }

        private void btnFitting_Click(object sender, EventArgs e)
        {
            if (GlobalCache.TType == "0")
            {
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = @"WordrobeApp.exe";
                info.Arguments = GlobalCache.location;
                info.WindowStyle = ProcessWindowStyle.Maximized;
                Process pro = Process.Start(info);
            }
            else
            {
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = @"PhotoAlbum.exe";
                info.Arguments = GlobalCache.location;
                info.WindowStyle = ProcessWindowStyle.Maximized;
                Process pro = Process.Start(info); 
            }
        }

        private void rmidoor_Click(object sender, EventArgs e)
        { 
            ConfigurationManager.AppSettings["ttype"] = GlobalCache.TType = "0";
            rmiWardrobe.IsChecked = true;
            rmiFitting.IsChecked = false;

            if (MsgBox.Ask("重启之后生效，是否重启？") == System.Windows.Forms.DialogResult.Yes)
            {
                result = System.Windows.Forms.DialogResult.Yes;
                this.mClose();
                Application.Restart();
            }
        }

        private void rmiFitting_Click(object sender, EventArgs e)
        {
            ConfigurationManager.AppSettings["ttype"] = GlobalCache.TType = "1";
            rmiWardrobe.IsChecked = false;
            rmiFitting.IsChecked = true;

            if (MsgBox.Ask("重启之后生效，是否重启？") == System.Windows.Forms.DialogResult.Yes)
            {
                result = System.Windows.Forms.DialogResult.Yes;
                this.mClose();
                Application.Restart();
            }
        }


        /// <summary>
        /// 消息信息
        /// </summary>
        private static Info info = null;
        /// <summary>
        /// 将消息推送到服务器
        /// </summary>
        /// <returns></returns>
        public Info GetInfo()
        {
            return info;
        }

        private String curBarcode = String.Empty;
        private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !String.IsNullOrEmpty(this.txtBarcode.Text) && curBarcode != this.txtBarcode.Text)
            {
                info = new Info() { type = InfoType.Info, message = this.txtBarcode.Text };
            }
        }

        private void btnconfig_Click(object sender, EventArgs e)
        {
            SysconfigFrm frm = new SysconfigFrm();
            frm.ShowDialog();
        }
    }
}
